﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;

namespace SqlProcessViewer
{
	public class DataRecordWrapper : DynamicObject
	{
		#region Variables

		private Dictionary<string, object> _record;

		#endregion

		#region Constructors

		public DataRecordWrapper(IDataRecord record)
		{
			_record = Enumerable
				.Range(0, record.FieldCount)
				.Select(x => record.GetName(x))
				.Distinct()
				.ToDictionary(name => name, name => record[name]);
		}

		#endregion

		#region Methods

		public override IEnumerable<string> GetDynamicMemberNames()
		{
			return _record.Keys;
		}

		public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
		{
			if (indexes.Length != 1)
			{
				throw new InvalidOperationException();
			}
			try
			{
				result = _record[indexes[0].ToString()];
				return true;
			}
			catch (Exception)
			{
				result = null;
				return false;
			}
		}

		public override bool TryGetMember(GetMemberBinder binder, out object result)
		{
			try
			{
				result = _record[binder.Name];
				return true;
			}
			catch (Exception)
			{
				result = null;
				return false;
			}
		}

		#endregion
	}
}